<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">盘点单新建</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm()"
                    >提交</el-button>
                </el-col>
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="单据编号:" prop="code">
                            <el-input v-model="form.code" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-input v-model="form.businessDate" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="计划开始:" prop="planStartTime">
                            <el-date-picker value-format="yyyy-MM-dd" v-model="form.planStartTime"  suffix-icon="el-icon-date" type="date" placeholder="" :picker-options="pickerOptions" style="width:100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="计划结束:" prop="planEndTime">
                            <el-date-picker value-format="yyyy-MM-dd" v-model="form.planEndTime" suffix-icon="el-icon-date" type="date" placeholder="" :picker-options="pickerOptions" style="width:100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="实际开始:" prop="startTime">
                            <el-input v-model="form.startTime" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="实际结束:" prop="endTime">
                            <el-input v-model="form.endTime" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="盘点仓库:">
                            <el-radio-group v-model="form.warehouseId" @change="onWarehouse">
                                <el-radio v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseId" style="margin-top:15px;">{{ item.name }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-col :span="9">
                            <el-form-item label="盘点类型:" prop="stocktakingType">
                                <el-select v-model="form.stocktakingType" style="width:100%;" placeholder="请选择" @change="onStocktakingType">
                                    <el-option label="按仓库盘点" value="0"></el-option>
                                    <el-option label="按产品盘点" value="1"></el-option>
                                    <el-option label="按区域" value="2"></el-option>
                                    <el-option label="按产品分类" value="3"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col :span="24" v-if="form.stocktakingType == '1'">
                        <el-col :span="24">
                            <el-col :span="9">
                                <el-form-item label="商品选择:">
                                    <el-autocomplete
                                        style="width:100%;"
                                        v-model="searchPro"
                                        :fetch-suggestions="searchCode"
                                        placeholder="模糊检索添加SKU产品"
                                        :trigger-on-focus="false"
                                        @select="searchProduct"
                                    ></el-autocomplete>
                                </el-form-item>
                            </el-col>
                            <el-button
                                class="btn-success ml20"
                                type="primary"
                                @click="onSearchProduct"
                            >批量添加产品</el-button>
                        </el-col>
                        <el-col :span="9">
                            <div class="stock-container" v-if="form.contentList && form.contentList.length > 0">
                                <div v-for="(item, index) in form.contentList" :key="index" class="stock-item">
                                    {{ item.specificationName }}
                                    <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-delete"
                                        @click="onProductDelete(item)"
                                    ></el-button>
                                </div>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="24" v-if="form.stocktakingType == '2'">
                        <el-col :span="9">
                            <el-form-item label="区域:">
                                <el-select v-model="area" style="width:100%;" placeholder="请选择" @change="onArea">
                                    <el-option
                                        v-for="item in areaList"
                                        :key="item.warehouseId"
                                        :label="item.name"
                                        :value="item.warehouseId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <div class="stock-container" v-if="form.contentList && form.contentList.length > 0">
                                <div v-for="(item, index) in form.contentList" :key="index" class="stock-item">
                                    {{ item.areaName }}
                                    <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-delete"
                                        @click="onAreaDelete(item)"
                                    ></el-button>
                                </div>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="24" v-if="form.stocktakingType == '3'">
                        <el-col :span="9">
                            <el-form-item>
                                <el-button
                                    class="btn-success"
                                    type="primary"
                                    @click="onProductClass"
                                >选择产品分类</el-button>
                            </el-form-item>
                            <div class="stock-container" v-if="form.contentList && form.contentList.length > 0">
                                <div v-for="(item, index) in form.contentList" :key="index" class="stock-item">
                                    {{ item.sortName }}
                                    <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-delete"
                                        @click="onProductClassDelete(item)"
                                    ></el-button>
                                </div>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="盘点负责人:" prop="personInCharge">
                            <el-input v-model="form.personInCharge" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="库管:" prop="libraryTube">
                            <el-input v-model="form.libraryTube" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 产品列表 -->
        <el-dialog title="产品列表" :visible.sync="showSkuProduct" width="800px" top="100px" append-to-body center :close-on-click-modal='false'>
            <el-table :data="showSkuProductList" ref="materialTablePro" @selection-change="selectionSkuProduct" :row-key="getRowKeys">
                <el-table-column type="selection" width="35" align="center" :reserve-selection="true" />
                <el-table-column label="序号" type="index" align="center" width="50">
                    <template slot-scope="scope">
                        <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="产品编码" align="center" prop="specificationCode" />
                <el-table-column label="产品名称" align="center" prop="specificationName" />
            </el-table>
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="onSearchProduct()"
            />
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="btn-success width100" @click="onHide">确定</el-button>
            </div>
        </el-dialog>
        <!-- 产品分类 -->
        <el-dialog title="产品分类" :visible.sync="showProductClass" width="800px" top="100px" append-to-body center :close-on-click-modal='false'>
            <el-table :data="showProductClassList" ref="materialTableProClass" @selection-change="selectionProductClassList" :row-key="getRowKeys">
                <el-table-column type="selection" width="35" align="center" :reserve-selection="true" />
                <el-table-column label="序号" type="index" align="center" width="50" />
                <el-table-column label="分类名称" align="center" prop="sortName" />
                <el-table-column label="分类编码" align="center" prop="sortCode" />
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" class="btn-success width100" @click="onHideClass">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { stocktakingAdd, searchWarehouseSku, searchWarehouseSort } from "@/api/system/stocktaking/stocktaking"
import { queryWarehouse, warehouseList } from "@/api/system/warehouse/warehouse"
export default {
    name: "add",
    data() {
        return {
            form: {
                id: '', // 单据id
                code: '', // 单据编号
                businessDate: '', // 业务日期
                planStartTime: '', // 计划开始
                planEndTime: '', // 计划结束
                startTime: '', // 实际开始
                endTime: '', // 实际结束
                remark: '', // 备注
                personInCharge: '', // 盘点负责人
                stocktakingType: '0', // 盘点类型
                libraryTube: '', // 库管
                warehouseId: '', // 仓库id
                warehouseName: '',// 仓库名称
                contentList: [], // 盘点内容
            },
            // 日期控制
            pickerOptions: {
                // disabledDate(time) {
                //     return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                // }
            },
            warehouseList: [], // 仓库列表
            warehouseAllList: [], // 仓库列表所有信息
            searchPro: '', // 产品搜索
            area: '', // 区域
            areaList: [], // 区域列表
            searchProductList: [], // 仓库搜索sku列表
            showSkuProduct: false, // 批量添加产品弹窗
            showSkuProductList: [], // 批量添加产品数据
            dataProductList: [],
            showProductClass: false, // 产品分类弹窗
            showProductClassList: [], // 产品分类数据
            dataProductClassList: [],
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                warehouseId: '',
            },
        }
    },
    created() {
        this.getWarehouseList()
        this.getWarehouseListAll()
    },
    methods: {
        // 盘点类型
        onStocktakingType(val){
            if(this.form.warehouseId !== ''){
                // 0按仓库盘点 1按产品盘点 2按区域 3按产品分类
                this.form.contentList = []
                if(val == '1'){
                    this.queryParams.warehouseId = this.form.warehouseId
                    this.getSearchWarehouseSku()
                }else if(val == '2'){
                    // 获取区域列表
                    let arr = this.warehouseAllList.find(item => item.warehouseId == this.form.warehouseId)
                    this.areaList = arr.children
                }
            }else{
                this.form.stocktakingType = ''
                this.$modal.msgError('请选择盘点仓库！')
            }
        },
        // 获取仓库所有信息
        getWarehouseListAll(){
            warehouseList().then(res => {
                this.warehouseAllList = res.data[0].children
            })
        },
        // 获取仓库列表
        getWarehouseList(){
            queryWarehouse().then(res => {
                if(res.code == 200){
                    this.warehouseList = res.data
                }
            })
        },
        // 仓库选择
        onWarehouse(val){
            this.form.contentList = []
            this.form.stocktakingType = '0'
            this.searchPro = ''
            let data = this.warehouseList.find(item => item.warehouseId == val)
            this.form.warehouseName = data.name
            if(this.dataProductList && this.dataProductList.length > 0){
                this.$refs.materialTablePro.clearSelection()
            }
            if(this.dataProductClassList && this.dataProductClassList.length > 0){
                this.$refs.materialTableProClass.clearSelection()
            }
        },
        // 根据仓库搜索sku列表
        getSearchWarehouseSku(){
            searchWarehouseSku({warehouseId: this.form.warehouseId}).then(res => {
                if(res.code == 200){
                    this.searchProductList = res.rows
                }
            })
        },
        // 编码搜索
        searchCode(val, cb) {
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 产品搜索
        searchProduct(val){
            // console.log(val)
            let index = this.form.contentList.findIndex(item => item.specificationId == val.specificationId)
            this.searchPro = ''
            if(index == -1){
                this.form.contentList.push({
                    specificationId: val.specificationId,
                    specificationName: val.specificationName
                })
            }else{
                this.$modal.msgError('产品已存在，请重新选择！')
            }
        },
        // 批量添加产品
        onSearchProduct(){
            searchWarehouseSku(this.addDateRange(this.queryParams)).then(res => {
                if(res.code == 200){
                    this.showSkuProduct = true
                    this.showSkuProductList = res.rows
                    this.total = res.total
                }
            })
        },
        // 选中产品
        selectionSkuProduct(row){
            this.dataProductList = row.map(item => item)
        },
        // 关闭
        onHide(){
            this.showSkuProduct = false
            this.form.contentList = []
            if(this.dataProductList && this.dataProductList.length > 0){
                this.dataProductList.map(item => {
                    this.form.contentList.push({
                        specificationId: item.specificationId,
                        specificationName: item.specificationName
                    })
                })
            }
        },
        // 区域选择
        onArea(val){
            // 判断区域是否存在
            let index = this.form.contentList.findIndex(item => item.areaId == val)
            this.area = ''
            if(index == -1){
                let data = this.areaList.find(item => item.warehouseId == val)
                this.form.contentList.push({
                    areaId: data.warehouseId,
                    areaName: data.name
                })
            }else{
                this.$modal.msgError('区域已存在，请重新选择！')
            }
        },
        // 选择产品分类
        onProductClass(){
            searchWarehouseSort(this.form.warehouseId).then(res => {
                if(res.code == 200){
                    this.showProductClass = true
                    this.showProductClassList = res.data
                }
            })
        },
        // 选中分类
        selectionProductClassList(row){
            this.dataProductClassList = row.map(item => item)
        },
        // 关闭分类弹窗
        onHideClass(){
            this.showProductClass = false
            this.form.contentList = []
            if(this.dataProductClassList && this.dataProductClassList.length > 0){
                this.dataProductClassList.map(item => {
                    this.form.contentList.push({
                        sortId: item.id,
                        sortName: item.sortName
                    })
                })
            }
        },
        // 翻页不清空
        getRowKeys(row){
            return row.id
        },
        // 删除区域
        onAreaDelete(item){
            let index = this.form.contentList.findIndex(i => {
              return i.areaId == item.areaId
            })
            this.form.contentList.splice(index, 1)
        },
        // 删除产品
        onProductDelete(item){
            let index = this.form.contentList.findIndex(i => {
              return i.specificationId == item.specificationId
            })
            this.form.contentList.splice(index, 1)
            this.dataProductList.find(y => {
                if(y.specificationId == item.specificationId){
                    this.$refs.materialTablePro.toggleRowSelection(y, false)
                }
            })
        },
        // 删除产品分类
        onProductClassDelete(item){
            let index = this.form.contentList.findIndex(i => {
                return i.sortId == item.sortId
            })
            this.form.contentList.splice(index, 1)
            this.dataProductClassList.find(y => {
                if(y.id == item.sortId){
                    this.$refs.materialTableProClass.toggleRowSelection(y, false)
                }
            })
        },
        // 确定
        submitForm(e){
            // console.log(this.form)
            // 判断是否选择仓库
            if(this.form.warehouseId !== ''){
                // 提交
                stocktakingAdd(this.form).then(res => {
                    if(res.code == 200){
                        this.$modal.msgSuccess("新建成功")
                        this.$tab.closeOpenPage({ path: "/warehouseManagement/warehouse/stocktaking" })
                    }
                })
            }else{
                this.$modal.msgError('请选择盘点仓库！')
            }
        }
    }
}
</script>

<style scoped>
.stock-container {
    margin: 0 0 22px 100px;
}
.stock-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 35px;
}
</style>